package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired(required = false)
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    //登入业务
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee){
        //1.调用业务登入
        R<Employee> r = employeeService.login(employee);

        //2.判断登入是否成功,成功就写入session
        if (r.getCode()==1){
            session.setAttribute("employee",r.getData().getId());
        }
        //返回数据
        return r;
    }

    //退出业务
    @RequestMapping("/logout")
    public R<String> logout(){
        session.invalidate();
        return R.success("退出成功");
    }

    //添加员工业务
    @PostMapping
    public R<String> save(@RequestBody Employee employee){
        //1.获取登入数据中存储的id
        Long id = (Long) session.getAttribute("employee");

        //2.完善数据
        //创建人
        employee.setCreateUser(id);

        //修改人
        employee.setUpdateUser(id);

        //调用业务
        employeeService.save(employee);

        return R.success("添加成功");
    }

    //根据姓名查询员工列表
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page, Integer pageSize, String name){
        Page<Employee> pageOjb = employeeService.findByPage(page, pageSize, name);
        return R.success(pageOjb);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee){
        //1.获取当前操作人的id
        Long id = (Long) session.getAttribute("employee");

        //2.完善修改人数据
        employee.setUpdateUser(id);

        //调用业务层方法修改
        employeeService.update(employee);

        //返回数据
        return R.success("修改成功");
    }

    //回显数据
    @RequestMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        return employeeService.findById(id);
    }
}
